package com.example.myspringboot.netty;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author cy
 * @date 2024/2/20
 */
public class ReadTimeoutHandler extends ChannelInboundHandlerAdapter {
    private static final Log log = LogFactory.get();

    /**
     * 用户事件触发方法的重写
     *
     * @param ctx ChannelHandlerContext对象
     * @param evt 事件对象
     * @throws Exception 异常
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            switch (event.state()) {
                case READER_IDLE:
                    log.info("Reader idle detected, closing the connection...");
                    // 处理读超时逻辑，例如关闭连接
                    ctx.close().addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
                    break;
                case WRITER_IDLE:
                    log.info("Writer idle detected, sending a heartbeat message...");
                    // 处理写超时逻辑，例如发送心跳包
                    break;
                case ALL_IDLE:
                    log.info("Both reader and writer are idle, checking the connection...");
                    // 处理读写都超时的情况
                    break;
                default:
                    break;
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
